package com.library.Fitter;

import com.library.Entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//过滤器
//拦截所有非法访问请求
@WebFilter("/*")
public class Filter implements javax.servlet.Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        javax.servlet.Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //拦截基于Http的请求
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String url = request.getRequestURI();
//        System.out.println(url);


        //放行主页、登录、注册界面
        if(url.contains("user.jsp")||url.contains("library.jsp")||url.contains("index.jsp")||url.contains("userregister")){
            filterChain.doFilter(request,response);
            return;
        }

        //放行静态资源如js，css，res
        if(url.contains("/JS")||url.contains("/CSS")||url.contains("/res")){
            filterChain.doFilter(request,response);
            return;
        }

        //放行登录、注册功能
        if(url.contains("login")){
            filterChain.doFilter(request,response);
            return;
        }

        //用户登录后放行所有界面
        User user = (User) request.getSession().getAttribute("userSeccess");
        if(user != null){
            filterChain.doFilter(request,response);
            return;
        }

        response.sendRedirect("user.jsp");

    }

    @Override
    public void destroy() {
        javax.servlet.Filter.super.destroy();
    }
}
